package externalApp.consumeservice;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;
import org.smartercontext.contextmger.communication.Communication_Impl;
import org.smartercontext.contextmger.communication.Communication_ImplProxy;

/**
 * Servlet implementation class ServletConsume
 */
@WebServlet("/ServletConsume")
public class ServletConsume extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletConsume() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	PrintWriter out = response.getWriter();
    	
    	if(request.getQueryString()!=null){
    		String usernameSearh = request.getParameter("usernameSearch");
    		String format = request.getParameter("format");
    		
    		if(usernameSearh!=null&&usernameSearh!=""){
    			
    			Communication_Impl comimpl = new Communication_ImplProxy();
    			String returned=comimpl.provideContext(usernameSearh, "all", format);
    			
    			if(returned!=null){
    				
    				if(format.equals("json")){
    					try {
    						if(returned.equals("The user has not granted any permissions")){
    							out.println("The user has not granted any permissions");
    						}else{
							JSONObject obj = new JSONObject(returned);
							out.println(obj);
    						}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
    				}else{
    					out.println(returned);
    				}
    				
    				
    				
    				
    			}
    			
    		}else{
    			out.println("Please try again!!");
    		}
    	}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
